package com.sky.utils;

import com.sky.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;

@Component
public class RedisCleanCacheUtil {

    @Autowired
    private  RedisTemplate redisTemplate;

    public  void cleanAllKeyByPattern(String pattern){
        if (pattern == null || pattern.isEmpty()) throw new BaseException("关键参数pattern未传递,pattern为：" + pattern);

        Set keys = redisTemplate.keys(pattern);

        if (keys == null || keys.isEmpty()) throw new BaseException("通过pattern查询不到key,pattern为：" + pattern);


        redisTemplate.delete(keys);

    }


    public  void cleanHash(String key,String ... hashKeys){
        if ((key == null || key.isEmpty()) || (hashKeys==null || hashKeys.length == 0)) throw  new BaseException("关键参数key或hashkey未传递,key为：" + key + "hashKey为："+hashKeys);
        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            Arrays.stream(hashKeys).forEach(e->{
                hashOperations.delete(key,e);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
